#include "MSD.h"
#include "app_data.h"
void listDir(fs::FS &fs, const char *dirname, uint8_t levels)
{
    Serial.printf("Listing directory: %s\n", dirname);

    File root = fs.open(dirname);
    if (!root)
    {
        Serial.println("Failed to open directory");
        return;
    }
    if (!root.isDirectory())
    {
        Serial.println("Not a directory");
        return;
    }

    File file = root.openNextFile();
    while (file)
    {
        if (file.isDirectory())
        {
            Serial.print("  DIR : ");
            Serial.println(file.name());
            if (levels)
            {
                listDir(fs, file.path(), levels - 1);
            }
        }
        else
        {
            Serial.print("  FILE: ");
            Serial.print(file.name());
            Serial.print("  SIZE: ");
            Serial.println(file.size());
        }
        file = root.openNextFile();
    }
}

void createDir(fs::FS &fs, const char *path)
{
    Serial.printf("Creating Dir: %s\n", path);
    if (fs.mkdir(path))
    {
        Serial.println("Dir created");
    }
    else
    {
        Serial.println("mkdir failed");
    }
}

void removeDir(fs::FS &fs, const char *path)
{
    Serial.printf("Removing Dir: %s\n", path);
    if (fs.rmdir(path))
    {
        Serial.println("Dir removed");
    }
    else
    {
        Serial.println("rmdir failed");
    }
}

void readFile(fs::FS &fs, const char *path)
{
    Serial.printf("Read file: %s\n", path);

    File file = fs.open(path);
    if (!file)
    {
        Serial.println("Read failure");
        return;
    }

    Serial.print("Begin read: ");
    while (file.available())
    {
        Serial.write(file.read());
    }
    file.close();
}

void writeFile(fs::FS &fs, const char *path, const char *message)
{
    Serial.printf("Writing file: %s\n", path);

    File file = fs.open(path, FILE_WRITE);
    if (!file)
    {
        Serial.println("Failed to open file for writing");
        return;
    }
    if (file.print(message))
    {
        Serial.println("File written");
    }
    else
    {
        Serial.println("Write failed");
    }
    file.close();
}

void appendFile(fs::FS &fs, const char *path, const char *message)
{
    Serial.printf("Appending to file: %s\n", path);

    File file = fs.open(path, FILE_APPEND);
    if (!file)
    {
        Serial.println("Failed to open file for appending");
        return;
    }
    if (file.print(message))
    {
        Serial.println("Message appended");
    }
    else
    {
        Serial.println("Append failed");
    }
    file.close();
}

void renameFile(fs::FS &fs, const char *path1, const char *path2)
{
    Serial.printf("Renaming file %s to %s\n", path1, path2);
    if (fs.rename(path1, path2))
    {
        Serial.println("File renamed");
    }
    else
    {
        Serial.println("Rename failed");
    }
}

void deleteFile(fs::FS &fs, const char *path)
{
    Serial.printf("Deleting file: %s\n", path);
    if (fs.remove(path))
    {
        Serial.println("File deleted");
    }
    else
    {
        Serial.println("Delete failed");
    }
}

void testFileIO(fs::FS &fs, const char *path)
{
    File file = fs.open(path);
    static uint8_t buf[512];
    size_t len = 0;
    uint32_t start = millis();
    uint32_t end = start;
    if (file)
    {
        len = file.size();
        size_t flen = len;
        start = millis();
        while (len)
        {
            size_t toRead = len;
            if (toRead > 512)
            {
                toRead = 512;
            }
            file.read(buf, toRead);
            len -= toRead;
        }
        end = millis() - start;
        Serial.printf("%u bytes read for %u ms\n", flen, end);
        file.close();
    }
    else
    {
        Serial.println("Failed to open file for reading");
    }

    file = fs.open(path, FILE_WRITE);
    if (!file)
    {
        Serial.println("Failed to open file for writing");
        return;
    }

    size_t i;
    start = millis();
    for (i = 0; i < 2048; i++)
    {
        file.write(buf, 512);
    }
    end = millis() - start;
    Serial.printf("%u bytes written for %u ms\n", 2048 * 512, end);
    file.close();
}
// void read_key_map(fs::FS &fs)
// {
//       File file = fs.open("/key_app1_map.txt");
//       if (!file)
//       {
//             return;
//       }
//       String map_data = "";
//       uint16_t data_num = 0;
//       while (file.available())
//       {
//             map_data += (char)file.read();
//             data_num++;
//       }
//       file.close();
//       String key_data = "";
//       uint8_t key1 = 0;
//       uint8_t key2 = 0;
//       uint8_t keynum = 0;
//       for (uint16_t num = 0; num < data_num; num++)
//       {
//             if (map_data[num] == ',' or map_data[num] == '.')
//             {
//                   if (keynum == 1)
//                   {
//                         key_app1_map[key1][key2] = (char)key_data[0];
//                   }
//                   else if (key_data == "null")
//                   {
//                         key_app1_map[key1][key2] = NULL;
//                   }
//                   else if (key_data == "ctrl")
//                   {
//                         key_app1_map[key1][key2] = KEY_LEFT_CTRL;
//                   }
//                   else if (key_data == "shift")
//                   {
//                         key_app1_map[key1][key2] = KEY_LEFT_SHIFT;
//                   }
//                   else if (key_data == "alt")
//                   {
//                         key_app1_map[key1][key2] = KEY_LEFT_ALT;
//                   }
//                   else if (key_data == "gui")
//                   {
//                         key_app1_map[key1][key2] = KEY_LEFT_GUI;
//                   }
//                   else if (key_data == "up")
//                   {
//                         key_app1_map[key1][key2] = KEY_UP_ARROW;
//                   }
//                   else if (key_data == "down")
//                   {
//                         key_app1_map[key1][key2] = KEY_DOWN_ARROW;
//                   }
//                   else if (key_data == "left")
//                   {
//                         key_app1_map[key1][key2] = KEY_LEFT_ARROW;
//                   }
//                   else if (key_data == "right")
//                   {
//                         key_app1_map[key1][key2] = KEY_RIGHT_ARROW;
//                   }
//                   else if (key_data == "backspace")
//                   {
//                         key_app1_map[key1][key2] = KEY_BACKSPACE;
//                   }
//                   else if (key_data == "tab")
//                   {
//                         key_app1_map[key1][key2] = KEY_TAB;
//                   }
//                   else if (key_data == "return")
//                   {
//                         key_app1_map[key1][key2] = KEY_RETURN;
//                   }
//                   else if (key_data == "esc")
//                   {
//                         key_app1_map[key1][key2] = KEY_ESC;
//                   }
//                   else if (key_data == "del")
//                   {
//                         key_app1_map[key1][key2] = KEY_DELETE;
//                   }
//                   else if (key_data == "home")
//                   {
//                         key_app1_map[key1][key2] = KEY_HOME;
//                   }
//                   else if (key_data == "end")
//                   {
//                         key_app1_map[key1][key2] = KEY_END;
//                   }
//                   else
//                   {
//                         key_app1_map[key1][key2] = NULL;
//                   }
//                   key2++;
//                   if (key2 == 3)
//                   {
//                         key2 = 0;
//                         key1++;
//                   }
//                   key_data = "";
//                   keynum = 0;
//                   if (map_data[num] == '.')
//                   {
//                         num += 2;
//                   }
//             }
//             else
//             {
//                   key_data += map_data[num];
//                   keynum++;
//             }
//       }
// }

SPIClass sdSPI(FSPI);

void sd_begin()
{
    sdSPI.begin(SD_SCLK, SD_MISO, SD_MOSI, SD_CS);
    Serial.println("#################   MSD.cpp:   #################");
    if (!SD.begin(SD_CS, sdSPI, 80000000))
    {
        Serial.println("Card Mount Failed");
        return;
    }

    uint8_t cardType = SD.cardType();

    if (cardType == CARD_NONE)
    {
        Serial.println("No SD card attached");
        return;
    }

    Serial.print("SD Card Type: ");
    if (cardType == CARD_MMC)
    {
        Serial.println("MMC");
    }
    else if (cardType == CARD_SD)
    {
        Serial.println("SDSC");
    }
    else if (cardType == CARD_SDHC)
    {
        Serial.println("SDHC");
    }
    else
    {
        Serial.println("UNKNOWN");
    }

    uint64_t cardSize = SD.cardSize() / (1024 * 1024);
    Serial.printf("SD Card Size: %lluMB\r\n", cardSize);

    // listDir(SD, "/", 0);
    // createDir(SD, "/mydir");
    // listDir(SD, "/", 0);
    // removeDir(SD, "/mydir");
    // listDir(SD, "/", 2);
    // writeFile(SD, "/hello.txt", "Hello ");
    // appendFile(SD, "/hello.txt", "World!\n");
    // readFile(SD, "/hello.txt");
    // deleteFile(SD, "/foo.txt");
    // renameFile(SD, "/hello.txt", "/foo.txt");
    // readFile(SD, "/foo.txt");
    // testFileIO(SD, "/test.txt");
    // read_key_map(SD);
    Serial.printf("Total space: %lluMB\r\n", SD.totalBytes() / (1024 * 1024));
    Serial.printf("Used space: %lluMB\r\n", SD.usedBytes() / (1024 * 1024));
    //SD.end();
}

bool writeSD_off_state()
{
    // if (!SD.begin(SD_CS, sdSPI, 80000000))
    // {
    //     Serial.println("Card Mount Failed");
    //     return 0;
    // }
    File file = SD.open("/off_state.txt", FILE_WRITE);
    if (!file)
    {
        // SD.end();
        return 0;
    }
    file.printf("LPbrightness:%03d\n", lampdata_refresh.brightness);
    file.printf("LPcolort:%03d\n", lampdata_refresh.colorT);
    file.printf("UPstart1:%01d\n", USBdata_refresh.USB_OUT1);
    file.printf("UPstart2:%01d\n", USBdata_refresh.USB_OUT2);
    file.printf("UPstart3:%01d\n", USBdata_refresh.USB_OUT3);
    file.printf("UPstart4:%01d\n", USBdata_refresh.USB_OUT4);
    file.close();
    // SD.end();
    return 1;
}

bool readSD_off_state()
{
    // if (!SD.begin(SD_CS, sdSPI, 80000000))
    // {
    //     Serial.println("Card Mount Failed");
    //     return 0;
    // }
    File file = SD.open("/off_state.txt");

    if (!file)
    {
        // file.close();
        // SD.end();
        return 0;
    }

    String read_sd_off_data = "";
    while (file.available())
        read_sd_off_data += char(file.read());
    read_sd_off_data.replace("\n", ":");
    for (uint8_t i = 0; i < 6; i++)
    {
        read_sd_off_data.remove(0, read_sd_off_data.indexOf(":") + 1);
        String bbb = "";
        for (uint8_t a = 0; a < read_sd_off_data.indexOf(":"); a++)
            bbb += read_sd_off_data[a];
        switch (i)
        {
        case 0:
            lampdata_refresh.brightness = bbb.toInt();
            break;
        case 1:
            lampdata_refresh.colorT = bbb.toInt();
            break;
        case 2:
            USBdata_refresh.USB_OUT1 = bbb.toInt();
            break;
        case 3:
            USBdata_refresh.USB_OUT2 = bbb.toInt();
            break;
        case 4:
            USBdata_refresh.USB_OUT3 = bbb.toInt();
            break;
        case 5:
            USBdata_refresh.USB_OUT4 = bbb.toInt();
            break;
        }
        read_sd_off_data.remove(0, read_sd_off_data.indexOf(":") + 1);
        Serial.println(bbb.toInt());
    }
    file.close();
    // SD.end();
    return 1;
}

void readFile(const char *path)
{
    Serial.printf("Read file: %s\n", path);

    File file = SD.open(path);
    if (!file)
    {
        Serial.println("Read failure");
        return;
    }

    Serial.print("Begin read: ");
    while (file.available())
    {
        Serial.write(file.read());
    }
    file.close();
}
